package com.taotao.order.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.CookieUtils;
import com.taotao.common.utils.JsonUtils;
import com.taotao.order.pojo.OrderInfo;
import com.taotao.order.service.OrderService;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbUser;

/**
 * 订单确认界面controller
 * @author leaf
 *
 */
@Controller
public class OrderController {

	@Value("${COOKIE_CART_KEY}")
	private String COOKIE_CART_KEY;
	
	@Autowired
	private OrderService orderService;
	
	@RequestMapping("/order/order-cart")
	public String showOrderCart(HttpServletRequest request){
		Cookie[] cookies = request.getCookies();
		List<TbItem> list = getCartList(request);
		request.setAttribute("cartList", list);
		return "order-cart";
	}
	//从cookie中取购物车列表
	private List<TbItem> getCartList(HttpServletRequest request) {
		//使用CookieUtils取购物车列表
		String json = CookieUtils.getCookieValue(request, COOKIE_CART_KEY, true);
		//判断cookie中是否有值
		if (StringUtils.isBlank(json)) {
			//没有值返回一个空List
			return new ArrayList<>();
		} 
		//把json转换成list对象
		List<TbItem> list = JsonUtils.jsonToList(json, TbItem.class);
		return list;
	}
	
	@RequestMapping(value="/order/create",method=RequestMethod.POST)
	public String createOrder(OrderInfo orderInfo,HttpServletRequest request){
		TbUser user = (TbUser) request.getAttribute("user");
		orderInfo.setUserId(user.getId());
		orderInfo.setBuyerNick(user.getUsername());
		TaotaoResult result = orderService.createOrder(orderInfo);
		String orderId = result.getData().toString();
		request.setAttribute("orderId", orderId);
		request.setAttribute("payment", orderInfo.getPayment());
		
		DateTime dateTime = new DateTime();
		dateTime.plusDays(3);
		
		request.setAttribute("date",dateTime.toString("yyyy-MM-dd"));
		request.setAttribute("TT_CART", null);
		return "success";
	}
}
